#include "sdl2_lcd.h"
#include <stdio.h>

int sdl2_lcd_init(sdl2_lcd* lcd)
{
	int ret = 0;

	if (NULL == lcd) {
		return -1;
	}

	if (!lcd->cfg.fix.width || !lcd->cfg.fix.height) {
		return -1;
	}

	ret = SDL_Init(SDL_INIT_VIDEO);
	if (ret) {
		return -1;
	}

	lcd->priv.window = SDL_CreateWindow("lvgl",
	    SDL_WINDOWPOS_UNDEFINED,
	    SDL_WINDOWPOS_UNDEFINED,
	    lcd->cfg.fix.width,
	    lcd->cfg.fix.height,
	    SDL_WINDOW_SHOWN);
	if (NULL == lcd->priv.window) {
		printf("err: SDL_CreateWindow()\n");
		SDL_Quit();
		return -1;
	}

	lcd->priv.renderer = SDL_CreateRenderer(lcd->priv.window,
	    -1,
	    SDL_RENDERER_ACCELERATED);
	if (NULL == lcd->priv.renderer) {
		printf("err: SDL_CreateRenderer()\n");
		SDL_DestroyWindow(lcd->priv.window);
		SDL_Quit();
		return -1;
	}

	lcd->priv.texture = SDL_CreateTexture(lcd->priv.renderer,
	    // SDL_PIXELFORMAT_ARGB8888,
	    SDL_PIXELFORMAT_RGB565,
	    SDL_TEXTUREACCESS_STREAMING,
	    lcd->cfg.fix.width,
	    lcd->cfg.fix.height);
	if (NULL == lcd->priv.texture) {
		printf("err: SDL_CreateTexture()\n");
		SDL_DestroyRenderer(lcd->priv.renderer);
		SDL_DestroyWindow(lcd->priv.window);
		SDL_Quit();
		return -1;
	}

	/* fixed the first render black screen */
	SDL_RenderPresent(lcd->priv.renderer);

	return 0;
}

int sdl2_lcd_fill(sdl2_lcd* lcd, int x1, int y1, int x2, int y2, uint16_t* color)
{
	int ret = 0;
	int picth = 0;
	SDL_Rect rect;

	if (NULL == lcd) {
		return -1;
	}

	if (NULL == color) {
		return -1;
	}

	if (NULL == lcd->priv.renderer) {
		return -1;
	}

	if (NULL == lcd->priv.texture) {
		return -1;
	}

	if (x1 < 0 || x1 >= lcd->cfg.fix.width) {
		return -1;
	}

	if (y1 < 0 || y1 >= lcd->cfg.fix.height) {
		return -1;
	}

	if (x2 < 0 || x2 >= lcd->cfg.fix.width) {
		return -1;
	}

	if (y2 < 0 || y2 >= lcd->cfg.fix.height) {
		return -1;
	}

	rect.x = x1;
	rect.y = y1;
	rect.w = x2 - x1 + 1;
	rect.h = y2 - y1 + 1;

	/* rgb5656 formmat, pre pixel is 2 byte*/
	picth = rect.w * 2;
	ret = SDL_UpdateTexture(lcd->priv.texture, &rect, color, picth);
	if (ret) {
		printf("err: SDL_UpdateTexture(), ret = %d\n", ret);
		return -1;
	}

	ret = SDL_RenderCopy(lcd->priv.renderer, lcd->priv.texture, &rect, &rect);
	if (ret) {
		printf("err: SDL_RenderCopy(), ret = %d\n", ret);
		return -1;
	}

	SDL_RenderPresent(lcd->priv.renderer);

	return 0;
}

void sdl2_lcd_deinit(sdl2_lcd* lcd)
{
	if (NULL == lcd) {
		return;
	}

	if (lcd->priv.texture != NULL) {
		SDL_DestroyTexture(lcd->priv.texture);
	}

	if (lcd->priv.renderer != NULL) {
		SDL_DestroyTexture(lcd->priv.renderer);
	}

	if (lcd->priv.window != NULL) {
		SDL_DestroyTexture(lcd->priv.window);
	}

	SDL_Quit();
}
